<?php

namespace Respect\Http\Module;

use Respect\Http\Bootstrappable;
use Respect\Environment\EnvironmentableInterface;

class Content extends NegotiationAbstract implements Bootstrappable
{

    protected $typeMap = array(
        'text/html' => 'html',
        'application/json' => 'json',
        'application/xml' => 'xml',
    );

    public function __construct(EnvironmentableInterface $env)
    {
        $requestExtension = $env->getUriExtension();
        if (!empty($requestExtension)) {
            $extensions = explode('.', $requestExtension);
            foreach ($extensions as $ext) {
                $mime = array_search($ext, $this->typeMap, 1);
                if ($mime)
                    return $this->requested[$mime] = 1000;
            }
        } else {
            $this->requested = $this->parseHeader($env['HTTP_ACCEPT']);
        }
        if (isset($this->requested['*/*'])) {
            unset($this->requested['*/*']);
        }
        if (empty($this->requested)) {
            $this->requested = array(
                'text/html' => 1000
            );
        }
    }

    public static function qualify(EnvironmentableInterface $env)
    {
        return $env['HTTP_ACCEPT'] ? new static($env) : false;
    }

    public function negotiateExtension($availableExtensions)
    {
        $mimetypes = array();
        foreach ($availableExtensions as $extension) {
            $mime = array_search($extension, $this->typeMap);
            if ($mime)
                $mimetypes[] = $mime;
        }
        if (isset($this->typeMap[$this->negotiate($mimetypes)])) {
            return $this->typeMap[$this->negotiate($mimetypes)];
        }
    }

}
